package com.water.camera.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.water.camera.databinding.PointItemBinding;
import com.water.camera.fragment.EditPointDlg;
import com.water.camera.util.Utils;

public class PointAdapter extends RecyclerView.Adapter {

    int select;
    EditPointDlg dlg;

    public PointAdapter(EditPointDlg dlg, int now) {
        this.dlg = dlg;
        this.select = now;
    }

    public int getSelect() {
        return select;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        PointItemBinding binding = PointItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return Utils.PATTERN.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        PointItemBinding binding;

        public Holder(PointItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            String s = Utils.PATTERN.get(p);
            s = Utils.currentPatternContent(40.145180, 116.699118, s);
            binding.tv.setText(s);
            if (select == p) {
                binding.img.setVisibility(View.VISIBLE);
            } else {
                binding.img.setVisibility(View.INVISIBLE);
            }
            itemView.setOnClickListener(v -> {
                int old = select;
                select = getBindingAdapterPosition();
                binding.img.setVisibility(View.VISIBLE);
                if (old >= 0) {
                    notifyItemChanged(old);
                }
            });
        }
    }
}
